﻿using System.IO;
using System;

namespace Gamemaster.Console
{
    public abstract class Command : ICommand
    {
        public TextWriter Out { get; set; }
        public bool Help { get; set; }

        public Command(params string[] args)
        {
            Out = new StringWriter();
            ParseArgs(args);
        }

        public void Execute()
        {
            if (Help)
            {
                PrintHelp();
            }
            else
            {
                Validate();
                RunCommand();
            }
        }
        public void ParseArgs(params string[] args)
        {
            foreach (string arg in args)
            {
                switch (arg.ToLower())
                {
                    case "?":
                    case "/?":
                    case "help":
                    case "/help":
                        Help = true;
                        break;
                    default:
                        Parameter param = new Parameter(arg);
                        HandleParameter(param);
                        if (!param.Handled)
                        {
                            throw new ArgumentException("Unrecognized argument", arg);
                        }
                        break;
                }
            }
        }
        public virtual void PrintHelp()
        {
            Out.WriteLine("GM command line tool Help");
        }

        protected abstract void Validate();
        protected abstract void RunCommand();
        protected abstract void HandleParameter(Parameter parameter);
    }
}
